package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.dao.*;
import cc.rengu.igas.bomp.common.dao.impl.*;
import cc.rengu.igas.bomp.common.entity.*;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.enums.BompImageUploadTypeEnum;
import cc.rengu.igas.bomp.facade.request.CreditReportQueryRequest;
import cc.rengu.igas.bomp.facade.response.CreditReportQueryResponse;
import cc.rengu.igas.share.common.util.GlobalEsbUtil;
import cc.rengu.igas.smps.facade.base.Header;
import cc.rengu.igas.smps.facade.request.PersonalCreditInquiryRequest;
import cc.rengu.igas.smps.facade.response.PersonalCreditInquiryResponse;
import cc.rengu.igas.smps.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/4/8 14:36
 * @description 征信查询
 */
public class CreditReportQueryService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        CreditReportQueryRequest reportQueryRequest = new CreditReportQueryRequest();
        ConvertUtil.convertOutput(reportQueryRequest);
        return reportQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        CreditReportQueryRequest queryRequest = (CreditReportQueryRequest) request;
        BizResponse<CreditReportQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);

        CreditReportQueryResponse queryResponse = new CreditReportQueryResponse();
        /*获取法人行号信息*/
        String instId = queryRequest.getHeader().getInstId();
        /*获取用户信息*/
        String userId = queryRequest.getUserId();
        /*获取法人姓名*/
        String artifName = queryRequest.getArtifName();
        /*获取法人证件号*/
        String certNo = queryRequest.getCertNo();
        /*获取商户号*/
        String mchntNo = queryRequest.getMchntNo();
        /*必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(artifName)
                || StringUtil.isEmptyOrNull(certNo) || StringUtil.isEmptyOrNull(mchntNo)) {
            rglog.error("必填性校验失败");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (null == mchntBaseInfo) {
            rglog.error("商户基础信息查询失败！instId:<{}>,mchntNo:<{}>",
                    queryRequest.getHeader().getInstId(), queryRequest.getMchntNo());
            throw new BizException(RespCodeEnum.QUERY_BASEDATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_BASEDATA_IS_NULL.getRespDesc());
        }

        SysParamMapper sysParamMapper = new SysParamMapperImpl();
        SysParam localImageStoragePath = sysParamMapper.selectSysParamByPrimaryKey(instId, BompAppParamConstant.IMAGE_STORAGE_PARAM_TYPE, BompAppParamConstant.LOCAL_IMAGE_STORAGE_PATH);
        SysParam sysParam = sysParamMapper.selectSysParamByPrimaryKey(instId, BompAppParamConstant.IMAGE_STORAGE_PARAM_TYPE, BompImageUploadTypeEnum.CREDIT_REPORT.getImagePathKey());
        if (null == sysParam || null == localImageStoragePath) {
            rglog.error("查询系统参数表，获取征信报告存储服务器路径为空！");
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        PersonalCreditInquiryRequest pcisRequest = new PersonalCreditInquiryRequest();
        pcisRequest.setCustomerName(queryRequest.getArtifName());
        pcisRequest.setCertNo(queryRequest.getCertNo());
        pcisRequest.setCertType(queryRequest.getCertType());
        pcisRequest.setQueryType("03");
        Header queryHeader = new Header();
        queryHeader.setInstId(instId);
        queryHeader.setChanlId(ChannelEnum.BOMP.getChannelType());
        queryHeader.setSrcSysId(AppParamConstant.SYS_ID);
        queryHeader.setTxnNum(null);
        queryHeader.setTransDate(DateUtil.getCurrentDate());
        queryHeader.setTransTime(DateUtil.getCurrentTime());
        queryHeader.setTraceNo(GlobalEsbUtil.generateEsbSeqeuenceNumber(instId));
        pcisRequest.setHeader(queryHeader);

        String reportAddr = null;
        String checkResult;
        DubboService dubboService = new DubboServiceImpl();
        Result<PersonalCreditInquiryResponse> pcisResult = (Result<PersonalCreditInquiryResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_RISK_ALARM_SERVICE, "personalCreditInquiry", pcisRequest);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        if (null == pcisResult || !pcisResult.isSuccess()
                || !DubboMethodConstant.DUBBO_SUCCESS.equals(pcisResult.getResult().getRespCode())) {
            rglog.info("征信报文查询pcisSupService.pcisCreditInfoQuery 失败！");
            queryResponse.setRespCode(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode());
            queryResponse.setRespDesc(null == pcisResult ? RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc() : pcisResult.getResult().getRespDesc());
            if (null != pcisResult && (null == pcisResult.getResult() || StringUtil.isEmptyOrNull(pcisResult.getResult().getRespDesc()))) {
                checkResult = RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc();
            } else {
                checkResult = queryResponse.getRespDesc();
            }
            bizResponse.setResult(queryResponse);
        } else {
            //核查完成时间
            queryResponse.setCreditReportContent(Base64.encodeBase64String(pcisResult.getResult().getCreditReportInfo().getBytes()));
            queryResponse.setCreditReportNo(pcisResult.getResult().getCreditReportNo());
            queryResponse.setCreditReportSources(pcisResult.getResult().getCreditReportInfo());
            //上传征信报告
            reportAddr = uploadToServer(queryRequest, pcisResult.getResult(), sysParam, localImageStoragePath);
            queryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            queryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            checkResult = queryResponse.getRespDesc();
            if (StringUtil.isEmptyOrNull(pcisResult.getResult().getRespDesc())) {
                checkResult = RespCodeEnum.TRANS_SUCCESS.getRespDesc();
            }
        }

        insertCreditInvestigationData(queryRequest, mchntBaseInfo, reportAddr, checkResult);

        bizResponse.setRespCode(queryResponse.getRespCode());
        bizResponse.setRespDesc(queryResponse.getRespDesc());
        bizResponse.setResult(queryResponse);
        return bizResponse;
    }

    private void insertCreditInvestigationData(CreditReportQueryRequest queryRequest, MchntBaseInfo mchntBaseInfo, String reportAddr, String checkResult) throws Exception {
        CreditInvestigation creditInvestigation = new CreditInvestigation();
        String creditReportId = RandomUtil.getUUID();
        creditInvestigation.setId(creditReportId);
        creditInvestigation.setInstId(queryRequest.getHeader().getInstId());
        creditInvestigation.setArtifName(queryRequest.getArtifName());
        creditInvestigation.setArtifIdNo(queryRequest.getCertNo());
        creditInvestigation.setMchntNo(queryRequest.getMchntNo());
        creditInvestigation.setMchntName(mchntBaseInfo.getMchntName());
        creditInvestigation.setCheckTime(DateUtil.getCurrentDateTime("yyyyMMdd HH:mm:ss.SSS"));
        creditInvestigation.setCheckResult(checkResult);
        creditInvestigation.setReportAddr(reportAddr);
        creditInvestigation.setOprId(queryRequest.getUserId());
        creditInvestigation.setCreateTime(DateUtil.getCurrentDateTime("yyyyMMdd HH:mm:ss.SSS"));
        creditInvestigation.setSysSeqNum(queryRequest.getHeader().getTraceNo());
        //   creditInvestigation.setCheckPerson(queryRequest.getUserId());

        ManagerInfoMapper managerInfoMapper = new ManagerInfoMapperImpl();
        /*根据用户id查询当前用户信息*/
        if (ChannelEnum.BSPS.getChannelType().equals(queryRequest.getHeader().getChanlId())) {
            /*商户服务操作查询认证*/
            BompUserInfoMapper bompUserInfoMapper = new BompUserInfoMapperImpl();
            BspsUserInfo userInfo = bompUserInfoMapper.selectBompBspsUserInfoByUserId(queryRequest.getHeader().getInstId(), queryRequest.getUserId());
            if (null != userInfo) {
                ManagerInfo managerInfo = managerInfoMapper.selectManagerInfoByOpenId(queryRequest.getHeader().getInstId(), userInfo.getOpenId());
                if (null != managerInfo) {
                    creditInvestigation.setCheckInst(managerInfo.getSignInstId());
                    creditInvestigation.setCrtOrgId(managerInfo.getSignInstId());
                    //核查人存拓展经理员工号
                    creditInvestigation.setCheckPerson(managerInfo.getManagerId());
                }
            }
        } else {
            /*运营管理操作查询用户信息*/
            AuthUserMapper authUserMapper = new AuthUserMapperImpl();
            AuthUser authUser = authUserMapper.selectAuthUserById(queryRequest.getUserId());
            if (null != authUser) {
                //核查人存登录员工号
                creditInvestigation.setCheckPerson(authUser.getEmpNo());
                List<ManagerInfo> managerInfoList = managerInfoMapper.selectBompManagerInfoByManagerId(queryRequest.getHeader().getInstId(), authUser.getEmpNo());
                if (!CollectionUtils.isEmpty(managerInfoList)) {
                    ManagerInfo managerInfo = managerInfoList.get(0);
                    creditInvestigation.setCheckInst(managerInfo.getSignInstId());
                    creditInvestigation.setCrtOrgId(managerInfo.getSignInstId());
                } else {
                    creditInvestigation.setCrtOrgId(authUser.getOrgCode());
                }
            }
        }
        CreditInvestigationMapper creditInvestigationMapper = new CreditInvestigationMapperImpl();
        int dbResult = creditInvestigationMapper.insertCreditInvestigation(creditInvestigation);
        if (dbResult != 0) {
            rglog.error("登记商户征信查询记录查询表失败！");
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 征信报告文件生成
     */
    private String uploadToServer(CreditReportQueryRequest queryRequest, PersonalCreditInquiryResponse pcisResponse,
                                  SysParam sysParam, SysParam localImageStoragePath) throws IOException {
        //上传到服务器
        //共享文件夹路径：XXXX/IGAS/
        String prefixUrl;
        if (localImageStoragePath.getParamValue().trim().endsWith(File.separator)) {
            prefixUrl = localImageStoragePath.getParamValue().trim();
        } else {
            prefixUrl = localImageStoragePath.getParamValue().trim() + File.separator;
        }

        String shareUrl;
        if (sysParam.getParamValue().trim().endsWith(File.separator)) {
            shareUrl = sysParam.getParamValue().trim();
        } else {
            shareUrl = sysParam.getParamValue().trim() + File.separator;
        }
        /*  商户征信信息：XXXX/IGAS/  +  法人行标识/查询日期/证件号_征信文档*/
        String storagePath = prefixUrl + shareUrl + queryRequest.getHeader().getInstId() + File.separator
                + DateUtil.getCurrentDate() + File.separator + queryRequest.getCertNo() + "_征信报告.html";

        rglog.debug("imageStoragePath=[{}]", storagePath);
        File storageFile = new File(storagePath);
        if (!storageFile.exists()) {
            if (!storageFile.getParentFile().exists()) {
                storageFile.getParentFile().mkdirs();
            }
            storageFile.createNewFile();
        }

        //IO流操作
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(storageFile);
            outputStream.write(pcisResponse.getCreditReportInfo().getBytes());
            outputStream.flush();
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            //关闭流
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
            } catch (Exception e) {
                rglog.error(e.getMessage());
            }
        }

        String localPath = shareUrl + queryRequest.getHeader().getInstId() + File.separator
                + DateUtil.getCurrentDate() + File.separator + queryRequest.getCertNo() + "_征信报告.html";
        rglog.debug("localPath=[{}]", localPath);
        return localPath;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        CreditReportQueryResponse reportQueryResponse = (CreditReportQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(reportQueryResponse);
    }
}
